﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Diagnostics;
using Path = System.IO.Path;
using HandyControl.Controls;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using Common.Untils;
using System.Runtime.InteropServices;
using WindowsInput;
using Application = System.Windows.Application;
using Tryit.ViewModels;
using System.Windows.Automation;
using System.Threading;
using System.Text.Json;
using Tryit.LOLApi.Models;

namespace Tryit.Views
{
    /// <summary>
    /// Settings.xaml 的交互逻辑
    /// </summary>
    public partial class Settings : Page
    {
        private string programName = "client.exe"; // 英雄联盟客户端程序名
        private string findedPath = string.Empty;
        private bool find = false;//默认未找到
        private bool canStartClient = false;
        private InputSimulator simulator = new InputSimulator();
        private SettingsViewModel vm = null;
        private bool isInitialized = false;
        private CoordinatesConfig coordinatesConfig;
        private bool isCapturingCoordinates = false;
        private string currentCapturingElement = "";
        private RegionCoordinates _regionCoordinates;
        private const string REGION_COORDINATES_FILE = "region_coordinates.json";
        private bool _isCapturingRegionCoordinates = false;
        private string _currentRegionName = "";
        private TextBlock _currentRegionCoordinatesTextBlock = null;

        // 登录界面固定坐标（作为备用）
        private readonly System.Drawing.Point QQ_LOGIN_BUTTON = new System.Drawing.Point(960, 540);
        private readonly System.Drawing.Point QQ_ACCOUNT_FIELD = new System.Drawing.Point(960, 480);
        private readonly System.Drawing.Point QQ_PASSWORD_FIELD = new System.Drawing.Point(960, 520);
        private readonly System.Drawing.Point LOGIN_BUTTON = new System.Drawing.Point(960, 560);
        private readonly System.Drawing.Point SERVER_LIST_BUTTON = new System.Drawing.Point(960, 400);
        private readonly System.Drawing.Point CONFIRM_SELECTION_BUTTON = new System.Drawing.Point(960, 500);

        public Settings()
        {
            InitializeComponent();
            
            // 使用Prism的依赖注入获取ViewModel
            vm = (SettingsViewModel)DataContext;
            if (vm == null)
            {
                vm = new SettingsViewModel();
                DataContext = vm;
            }
            
            // 加载坐标配置
            LoadCoordinatesConfig();
            LoadRegionCoordinates();
            
            // 延迟初始化重量级组件
            Task.Run(async () =>
            {
                await InitializeComponentsAsync();
            });
        }

        private void LoadCoordinatesConfig()
        {
            string configPath = Path.Combine(Environment.CurrentDirectory, "coordinates.json");
            if (File.Exists(configPath))
            {
                try
                {
                    string json = File.ReadAllText(configPath);
                    coordinatesConfig = JsonSerializer.Deserialize<CoordinatesConfig>(json);
                    
                    // 更新界面显示
                    UpdateCoordinatesDisplay("QQLoginButtonCoordinates", $"({coordinatesConfig.QQLoginButton.X}, {coordinatesConfig.QQLoginButton.Y})");
                    UpdateCoordinatesDisplay("QQAccountFieldCoordinates", $"({coordinatesConfig.QQAccountField.X}, {coordinatesConfig.QQAccountField.Y})");
                    UpdateCoordinatesDisplay("QQPasswordFieldCoordinates", $"({coordinatesConfig.QQPasswordField.X}, {coordinatesConfig.QQPasswordField.Y})");
                    UpdateCoordinatesDisplay("LoginButtonCoordinates", $"({coordinatesConfig.LoginButton.X}, {coordinatesConfig.LoginButton.Y})");
                    UpdateCoordinatesDisplay("ServerListButtonCoordinates", $"({coordinatesConfig.ServerListButton.X}, {coordinatesConfig.ServerListButton.Y})");
                    UpdateCoordinatesDisplay("ConfirmSelectionButtonCoordinates", $"({coordinatesConfig.ConfirmSelectionButton.X}, {coordinatesConfig.ConfirmSelectionButton.Y})");
                    UpdateCoordinatesDisplay("ServerListStartYCoordinates", coordinatesConfig.ServerListStartY.ToString());
                    UpdateCoordinatesDisplay("ServerListXCoordinates", coordinatesConfig.ServerListX.ToString());
                    UpdateCoordinatesDisplay("ServerListIntervalCoordinates", coordinatesConfig.ServerListInterval.ToString());
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"加载坐标配置失败: {ex.Message}");
                    coordinatesConfig = new CoordinatesConfig();
                }
            }
            else
            {
                coordinatesConfig = new CoordinatesConfig();
            }
        }

        private void SaveCoordinatesConfig()
        {
            string configPath = Path.Combine(Environment.CurrentDirectory, "coordinates.json");
            try
            {
                string json = JsonSerializer.Serialize(coordinatesConfig, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(configPath, json);
                Growl.Success("坐标配置已保存");
            }
            catch (Exception ex)
            {
                Growl.Error($"保存坐标配置失败: {ex.Message}");
            }
        }

        private async Task InitializeComponentsAsync()
        {
            if (isInitialized) return;

            try
            {
                // 初始化buke_km
                if (!buke_km.Init(0, 0))
                {
                    Console.WriteLine("Failed to initialize buke_km");
                    return;
                }

                isInitialized = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to initialize components: {ex.Message}");
            }
        }

        private void InitClientPath()
        {
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo drive in drives)
            {
                if (find) break;
                if (drive.IsReady && drive.DriveType == DriveType.Fixed)
                {
                    var files = drive.EnumerateFiles().ToArray();
                    findedPath = files.Where(x => Path.GetFileName(x) == programName).FirstOrDefault();
                    if (!string.IsNullOrEmpty(findedPath))
                    {
                        find = true;
                        break;
                    }
                }
            }
            if (find)
            {
                Application.Current.Dispatcher.Invoke(() =>
            {
                ClientPath.Text = findedPath;
            });
            }
            else Growl.Warning("未找到客户端文件,请尝试手动添加");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "所有文件 (*.*)|*.*" // 可以根据需要设置文件过滤器
            };

            // 显示对话框并检查用户选择的文件
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取文件路径
                string filePath = openFileDialog.FileName;
                
                // 更新UI和ViewModel
                ClientPath.Text = filePath;
                
                // 确保ViewModel不为null
                if (vm == null)
                {
                    vm = (SettingsViewModel)DataContext;
                    if (vm == null)
                    {
                        vm = new SettingsViewModel();
                        DataContext = vm;
                    }
                }
                
                // 更新ClientAddress属性
                vm.ClientAddress = filePath;
                
                // 立即保存设置
                vm.SaveSettings.Execute();
            }
        }

        private async void Button_Click_StartClient(object sender, RoutedEventArgs e)
        {
            Check();
            if (canStartClient)
            {
                Process process = new Process();
                // 设置启动信息
                process.StartInfo.FileName = ClientPath.Text.Trim();
                process.Start();
                
                // 等待客户端加载完成
                await Task.Delay(15000);
                
                // 直接使用保存的坐标进行登录
                await PerformLoginWithSavedCoordinates();
            }
        }
        
        
        private async Task PerformLoginWithSavedCoordinates()
        {
            // 检查是否有保存的坐标
            if (coordinatesConfig == null || !coordinatesConfig.IsValid())
            {
                Growl.Warning("未找到有效的坐标配置，将使用默认坐标");
                await PerformLoginWithFixedCoordinates();
                return;
            }
            
            // 点击QQ登录按钮
            MoveMouseAndClickInClient(coordinatesConfig.QQLoginButton);
            await Task.Delay(2000); // 增加延迟，确保界面加载完成
            
            // 点击QQ账号输入框
            MoveMouseAndClickInClient(coordinatesConfig.QQAccountField);
            await Task.Delay(1000); // 增加延迟，确保鼠标移动完成
            simulator.Mouse.LeftButtonDoubleClick(); // 双击选中所有文本
            await Task.Delay(500); // 增加延迟，确保双击生效
            simulator.Keyboard.KeyPress(VirtualKeyCode.BACK); // 删除选中文本
            await Task.Delay(500); // 增加延迟，确保文本被删除
            
            // 输入账号 - 使用更可靠的方法
            string account = User.Text.Trim();
            if (!string.IsNullOrEmpty(account))
            {
                // 使用buke_km输入账号，这个方法更可靠
                InputTextInClient(account);
                await Task.Delay(1500); // 增加延迟，确保账号输入完成
            }
            else
            {
                Growl.Warning("账号为空，无法输入");
                return;
            }
            
            // 点击密码输入框
            MoveMouseAndClickInClient(coordinatesConfig.QQPasswordField);
            await Task.Delay(1000); // 增加延迟，确保鼠标移动完成
            simulator.Mouse.LeftButtonDoubleClick(); // 双击选中所有文本
            await Task.Delay(500);
            simulator.Keyboard.KeyPress(VirtualKeyCode.BACK); // 删除选中文本
            await Task.Delay(500); // 增加延迟，确保文本被删除
            
            // 输入密码 - 使用更可靠的方法
            string password = Password.Password;
            if (!string.IsNullOrEmpty(password))
            {
                // 使用buke_km输入密码，这个方法更可靠
                InputTextInClient(password);
                await Task.Delay(1500); // 增加延迟，确保密码输入完成
            }
            else
            {
                Growl.Warning("密码为空，无法输入");
                return;
            }
            
            // 点击进入游戏按钮
            MoveMouseAndClickInClient(coordinatesConfig.LoginButton);
            await Task.Delay(6000);
            
            // 选择服务器
            string selectedServer = CmbList.SelectedValue.ToString();
            
            // 尝试点击服务器列表按钮
            MoveMouseAndClickInClient(coordinatesConfig.ServerListButton);
            await Task.Delay(2000); // 增加延迟，确保服务器列表加载完成
            
            // 根据选择的服务器获取坐标
            System.Drawing.Point serverPoint = GetServerCoordinates(selectedServer);
            if (serverPoint.X > 0 && serverPoint.Y > 0)
            {
                // 点击服务器
                MoveMouseAndClickInClient(serverPoint);
                await Task.Delay(1000); // 增加延迟，确保点击生效
                
                // 点击确认选择按钮
                MoveMouseAndClickInClient(coordinatesConfig.ConfirmSelectionButton);
            }
            else
            {
                Growl.Warning($"未找到服务器 {selectedServer} 的坐标映射");
            }
        }
        
        private async Task PerformLoginWithFixedCoordinates()
        {
            // 点击QQ登录按钮
            MoveMouseAndClickInClient(new System.Drawing.Point(400, 300));
            await Task.Delay(1000);
            
            // 点击QQ账号输入框
            MoveMouseAndClickInClient(new System.Drawing.Point(400, 350));
            await Task.Delay(1000);
            simulator.Mouse.LeftButtonDoubleClick();
            await Task.Delay(500);
            simulator.Keyboard.KeyPress(VirtualKeyCode.BACK);
            await Task.Delay(1000);
            
            // 输入账号
            string account = User.Text.Trim();
            if (!string.IsNullOrEmpty(account))
            {
                InputTextInClient(account);
                await Task.Delay(1000);
                
                // 再次点击输入框
                MoveMouseAndClickInClient(new System.Drawing.Point(400, 350));
                await Task.Delay(500);
            }
            else
            {
                Growl.Warning("账号为空，无法输入");
                return;
            }
            
            // 点击密码输入框
            MoveMouseAndClickInClient(new System.Drawing.Point(400, 400));
            await Task.Delay(1000);
            simulator.Mouse.LeftButtonDoubleClick();
            await Task.Delay(500);
            simulator.Keyboard.KeyPress(VirtualKeyCode.BACK);
            await Task.Delay(1000);
            
            // 输入密码
            string password = Password.Password;
            if (!string.IsNullOrEmpty(password))
            {
                InputTextInClient(password);
                await Task.Delay(1000);
            }
            else
            {
                Growl.Warning("密码为空，无法输入");
                return;
            }
            
            // 点击进入游戏按钮
            MoveMouseAndClickInClient(new System.Drawing.Point(400, 450));
            await Task.Delay(6000);
            
            // 选择服务器
            string selectedServer = CmbList.SelectedValue.ToString();
            
            // 点击服务器列表按钮
            MoveMouseAndClickInClient(new System.Drawing.Point(400, 500));
            await Task.Delay(2000);
            
            // 根据选择的服务器获取坐标
            System.Drawing.Point serverPoint = GetServerCoordinates(selectedServer);
            if (serverPoint.X > 0 && serverPoint.Y > 0)
            {
                // 点击服务器
                MoveMouseAndClickInClient(serverPoint);
                await Task.Delay(1000);
                
                // 点击确认选择按钮
                MoveMouseAndClickInClient(new System.Drawing.Point(400, 550));
            }
            else
            {
                Growl.Warning($"未找到服务器 {selectedServer} 的坐标映射");
            }
        }

        // 获取服务器索引，用于计算点击位置
        private int GetServerIndex(string serverName)
        {
            string[] servers = {
                "艾欧尼亚", "祖安", "诺克萨斯", "班德尔城", "皮尔特沃夫", "战争学院", 
                "巨神峰", "雷瑟守备", "裁决之地", "黑色玫瑰", "暗影岛", "钢铁烈阳", 
                "水晶之痕", "均衡教派", "影流", "守望之海", "征服之海", "卡拉曼达", 
                "皮城警备", "比尔吉沃特", "德玛西亚", "弗雷尔卓德", "无畏先锋", "恕瑞玛", 
                "扭曲丛林", "巨龙之巢", "男爵领域", "峡谷之巅", "教育网专区"
            };
            
            return Array.IndexOf(servers, serverName);
        }

        private void Check()
        {
            if (string.IsNullOrEmpty(User.Text))
            {
                Growl.Warning("请输入账号!");
                return;
            }
            if (string.IsNullOrEmpty(Password.Password))
            {
                Growl.Warning("请输入密码!");
                return;
            }
            if (string.IsNullOrEmpty(ClientPath.Text))
            {
                Growl.Warning("请选择客户端文件!");
                return;
            }
            if (CmbList.SelectedItem == null)
            {
                Growl.Warning("请选择服务器!");
                return;
            }
            canStartClient = true;
        }

        private void User_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+"); // 除数字外的所有字符
            e.Handled = regex.IsMatch(e.Text); // 如果匹配则处理为 true
        }
        
        // 开始捕获坐标
        private void StartCapturingCoordinates(string elementName)
        {
            if (isCapturingCoordinates)
            {
                Growl.Warning("已经在捕获坐标中，请先完成当前捕获");
                return;
            }
            
            isCapturingCoordinates = true;
            currentCapturingElement = elementName;
            
            // 显示提示
            Growl.Info($"请将鼠标移动到 {elementName} 位置，然后按下 F2 键保存坐标");
            
            // 启动一个任务来监听F2键
            Task.Run(() =>
            {
                while (isCapturingCoordinates)
                {
                    // 检查F2键是否按下
                    if ((GetAsyncKeyState(0x71) & 0x8000) != 0) // 0x71 是F2键的虚拟键码
                    {
                        // 获取当前鼠标位置
                        POINT point;
                        GetCursorPos(out point);
                        
                        // 保存坐标
                        SaveCoordinates(elementName, point.X, point.Y);
                        
                        // 停止捕获
                        isCapturingCoordinates = false;
                        break;
                    }
                    
                    // 检查ESC键是否按下（取消捕获）
                    if ((GetAsyncKeyState(0x1B) & 0x8000) != 0) // 0x1B 是ESC键的虚拟键码
                    {
                        isCapturingCoordinates = false;
                        Growl.Warning("已取消坐标捕获");
                        break;
                    }
                    
                    Thread.Sleep(100);
                }
            });
        }
        
        // 保存坐标
        private void SaveCoordinates(string elementName, int x, int y)
        {
            if (coordinatesConfig == null)
            {
                coordinatesConfig = new CoordinatesConfig();
            }
            
            // 将屏幕坐标转换为客户端相对坐标
            System.Drawing.Point clientPoint = ScreenToClientCoordinates(new System.Drawing.Point(x, y));
            
            switch (elementName)
            {
                case "QQ登录按钮":
                    coordinatesConfig.QQLoginButton = clientPoint;
                    UpdateCoordinatesDisplay("QQLoginButtonCoordinates", $"({clientPoint.X}, {clientPoint.Y})");
                    break;
                case "QQ账号输入框":
                    coordinatesConfig.QQAccountField = clientPoint;
                    UpdateCoordinatesDisplay("QQAccountFieldCoordinates", $"({clientPoint.X}, {clientPoint.Y})");
                    break;
                case "QQ密码输入框":
                    coordinatesConfig.QQPasswordField = clientPoint;
                    UpdateCoordinatesDisplay("QQPasswordFieldCoordinates", $"({clientPoint.X}, {clientPoint.Y})");
                    break;
                case "进入游戏按钮":
                    coordinatesConfig.LoginButton = clientPoint;
                    UpdateCoordinatesDisplay("LoginButtonCoordinates", $"({clientPoint.X}, {clientPoint.Y})");
                    break;
                case "服务器列表按钮":
                    coordinatesConfig.ServerListButton = clientPoint;
                    UpdateCoordinatesDisplay("ServerListButtonCoordinates", $"({clientPoint.X}, {clientPoint.Y})");
                    break;
                case "确认选择按钮":
                    coordinatesConfig.ConfirmSelectionButton = clientPoint;
                    UpdateCoordinatesDisplay("ConfirmSelectionButtonCoordinates", $"({clientPoint.X}, {clientPoint.Y})");
                    break;
                case "服务器列表起始Y坐标":
                    coordinatesConfig.ServerListStartY = clientPoint.Y;
                    UpdateCoordinatesDisplay("ServerListStartYCoordinates", clientPoint.Y.ToString());
                    break;
                case "服务器列表X坐标":
                    coordinatesConfig.ServerListX = clientPoint.X;
                    UpdateCoordinatesDisplay("ServerListXCoordinates", clientPoint.X.ToString());
                    break;
                case "服务器列表间隔":
                    coordinatesConfig.ServerListInterval = clientPoint.Y;
                    UpdateCoordinatesDisplay("ServerListIntervalCoordinates", clientPoint.Y.ToString());
                    break;
            }
            
            // 保存配置
            SaveCoordinatesConfig();
            
            // 显示提示
            Growl.Success($"已保存 {elementName} 的坐标: ({clientPoint.X}, {clientPoint.Y})");
        }
        
        // 更新坐标显示
        private void UpdateCoordinatesDisplay(string elementName, string value)
        {
            // 使用Dispatcher确保在UI线程上更新
            Application.Current.Dispatcher.Invoke(() =>
            {
                // 查找对应的TextBlock并更新其文本
                var textBlock = this.FindName(elementName) as TextBlock;
                if (textBlock != null)
                {
                    textBlock.Text = value;
                }
            });
        }
        
        // 捕获QQ登录按钮坐标
        private void CaptureQQLoginButton_Click(object sender, RoutedEventArgs e)
        {
            StartCapturingCoordinates("QQ登录按钮");
        }
        
        // 捕获QQ账号输入框坐标
        private void CaptureQQAccountField_Click(object sender, RoutedEventArgs e)
        {
            StartCapturingCoordinates("QQ账号输入框");
        }
        
        // 捕获QQ密码输入框坐标
        private void CaptureQQPasswordField_Click(object sender, RoutedEventArgs e)
        {
            StartCapturingCoordinates("QQ密码输入框");
        }
        
        // 捕获进入游戏按钮坐标
        private void CaptureLoginButton_Click(object sender, RoutedEventArgs e)
        {
            StartCapturingCoordinates("进入游戏按钮");
        }
        
        // 捕获服务器列表按钮坐标
        private void CaptureServerListButton_Click(object sender, RoutedEventArgs e)
        {
            StartCapturingCoordinates("服务器列表按钮");
        }
        
        // 捕获确认选择按钮坐标
        private void CaptureConfirmSelectionButton_Click(object sender, RoutedEventArgs e)
        {
            StartCapturingCoordinates("确认选择按钮");
        }
        
        // 获取异步键状态
        [DllImport("user32.dll")]
        private static extern short GetAsyncKeyState(int vKey);
        
        // 获取光标位置
        [DllImport("user32.dll")]
        private static extern bool GetCursorPos(out POINT lpPoint);
        
        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            public int X;
            public int Y;
        }

        public class buke_km
        {
            public const string buke_km_dll_name = "buke_km64.dll";
            [DllImport(buke_km_dll_name, EntryPoint = "Init", CallingConvention = CallingConvention.Cdecl)]
            public static extern bool Init(Int32 pwd, byte key);

            [DllImport(buke_km_dll_name, EntryPoint = "SetScale", CallingConvention = CallingConvention.Cdecl)]
            public static extern void SetScale(float scale);

            [DllImport(buke_km_dll_name, EntryPoint = "SetMouseMoveTrack", CallingConvention = CallingConvention.Cdecl)]
            public static extern void SetMouseMoveTrack(Int32 delay, Int32 step);

            [DllImport(buke_km_dll_name, EntryPoint = "MouseMove", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseMove(Int32 x, Int32 y);

            [DllImport(buke_km_dll_name, EntryPoint = "MouseMoveR", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseMoveR(Int32 x, Int32 y);

            [DllImport(buke_km_dll_name, EntryPoint = "MouseLeftDown", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseLeftDown();

            [DllImport(buke_km_dll_name, EntryPoint = "MouseLeftUp", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseLeftUp();

            [DllImport(buke_km_dll_name, EntryPoint = "MouseRightDown", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseRightDown();

            [DllImport(buke_km_dll_name, EntryPoint = "MouseRightUp", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseRightUp();

            [DllImport(buke_km_dll_name, EntryPoint = "MouseMiddleDown", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseMiddleDown();

            [DllImport(buke_km_dll_name, EntryPoint = "MouseMiddleUp", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseMiddleUp();

            [DllImport(buke_km_dll_name, EntryPoint = "MouseWheelDown", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseWheelDown();

            [DllImport(buke_km_dll_name, EntryPoint = "MouseWheelUp", CallingConvention = CallingConvention.Cdecl)]
            public static extern void MouseWheelUp();

            [DllImport(buke_km_dll_name, EntryPoint = "KeyboardDown", CallingConvention = CallingConvention.Cdecl)]
            public static extern void KeyboardDown(Int32 key);

            [DllImport(buke_km_dll_name, EntryPoint = "KeyboardUp", CallingConvention = CallingConvention.Cdecl)]
            public static extern void KeyboardUp(Int32 key);

            [DllImport(buke_km_dll_name, EntryPoint = "InputString", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
            public static extern void InputString(string str);

            // 获取鼠标位置的方法
            public static Point GetMousePosition()
            {
                POINT point;
                GetCursorPos(out point);
                return new Point(point.X, point.Y);
            }
        }

        private void LoadRegionCoordinates()
        {
            _regionCoordinates = RegionCoordinates.LoadFromFile(REGION_COORDINATES_FILE);
            UpdateRegionCoordinatesDisplay();
        }

        private void UpdateRegionCoordinatesDisplay()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                IoniaCoordinates.Text = $"({_regionCoordinates.Ionia.X}, {_regionCoordinates.Ionia.Y})";
                ZaunCoordinates.Text = $"({_regionCoordinates.Zaun.X}, {_regionCoordinates.Zaun.Y})";
                NoxusCoordinates.Text = $"({_regionCoordinates.Noxus.X}, {_regionCoordinates.Noxus.Y})";
                BandleCityCoordinates.Text = $"({_regionCoordinates.BandleCity.X}, {_regionCoordinates.BandleCity.Y})";
                PiltoverCoordinates.Text = $"({_regionCoordinates.Piltover.X}, {_regionCoordinates.Piltover.Y})";
                WarCollegeCoordinates.Text = $"({_regionCoordinates.WarCollege.X}, {_regionCoordinates.WarCollege.Y})";
                MountTargonCoordinates.Text = $"({_regionCoordinates.MountTargon.X}, {_regionCoordinates.MountTargon.Y})";
                LeiSeCoordinates.Text = $"({_regionCoordinates.LeiSe.X}, {_regionCoordinates.LeiSe.Y})";
                JudgmentCoordinates.Text = $"({_regionCoordinates.Judgment.X}, {_regionCoordinates.Judgment.Y})";
                BlackRoseCoordinates.Text = $"({_regionCoordinates.BlackRose.X}, {_regionCoordinates.BlackRose.Y})";
                ShadowIslesCoordinates.Text = $"({_regionCoordinates.ShadowIsles.X}, {_regionCoordinates.ShadowIsles.Y})";
                IronSunCoordinates.Text = $"({_regionCoordinates.IronSun.X}, {_regionCoordinates.IronSun.Y})";
                CrystalScarCoordinates.Text = $"({_regionCoordinates.CrystalScar.X}, {_regionCoordinates.CrystalScar.Y})";
                EquilibriumCoordinates.Text = $"({_regionCoordinates.Equilibrium.X}, {_regionCoordinates.Equilibrium.Y})";
                ShadowStreamCoordinates.Text = $"({_regionCoordinates.ShadowStream.X}, {_regionCoordinates.ShadowStream.Y})";
                WatchSeaCoordinates.Text = $"({_regionCoordinates.WatchSea.X}, {_regionCoordinates.WatchSea.Y})";
                ConquerSeaCoordinates.Text = $"({_regionCoordinates.ConquerSea.X}, {_regionCoordinates.ConquerSea.Y})";
                KalamandaCoordinates.Text = $"({_regionCoordinates.Kalamanda.X}, {_regionCoordinates.Kalamanda.Y})";
                PiltoverPoliceCoordinates.Text = $"({_regionCoordinates.PiltoverPolice.X}, {_regionCoordinates.PiltoverPolice.Y})";
                BilgewaterCoordinates.Text = $"({_regionCoordinates.Bilgewater.X}, {_regionCoordinates.Bilgewater.Y})";
                DemaciaCoordinates.Text = $"({_regionCoordinates.Demacia.X}, {_regionCoordinates.Demacia.Y})";
                FreljordCoordinates.Text = $"({_regionCoordinates.Freljord.X}, {_regionCoordinates.Freljord.Y})";
                FearlessPioneerCoordinates.Text = $"({_regionCoordinates.FearlessPioneer.X}, {_regionCoordinates.FearlessPioneer.Y})";
                ShurimaCoordinates.Text = $"({_regionCoordinates.Shurima.X}, {_regionCoordinates.Shurima.Y})";
                TwistedTreelineCoordinates.Text = $"({_regionCoordinates.TwistedTreeline.X}, {_regionCoordinates.TwistedTreeline.Y})";
                DragonNestCoordinates.Text = $"({_regionCoordinates.DragonNest.X}, {_regionCoordinates.DragonNest.Y})";
                BaronRealmCoordinates.Text = $"({_regionCoordinates.BaronRealm.X}, {_regionCoordinates.BaronRealm.Y})";
                CanyonPeakCoordinates.Text = $"({_regionCoordinates.CanyonPeak.X}, {_regionCoordinates.CanyonPeak.Y})";
                EduNetCoordinates.Text = $"({_regionCoordinates.EduNet.X}, {_regionCoordinates.EduNet.Y})";
            });
        }

        private void StartRegionCoordinatesCapture(string regionName, TextBlock coordinatesTextBlock)
        {
            if (_isCapturingRegionCoordinates)
            {
                Growl.Warning("已经在捕获大区坐标中，请先完成当前捕获");
                return;
            }
            
            _isCapturingRegionCoordinates = true;
            _currentRegionName = regionName;
            _currentRegionCoordinatesTextBlock = coordinatesTextBlock;
            
            // 显示提示
            Growl.Info($"请将鼠标移动到 {regionName} 位置，然后按下 F2 键保存坐标");
            
            // 启动一个任务来监听F2键
            Task.Run(() =>
            {
                while (_isCapturingRegionCoordinates)
                {
                    // 检查F2键是否按下
                    if ((GetAsyncKeyState(0x71) & 0x8000) != 0) // 0x71 是F2键的虚拟键码
                    {
                        // 获取当前鼠标位置
                        POINT point;
                        GetCursorPos(out point);
                        
                        // 保存坐标
                        SaveRegionCoordinates(new Point(point.X, point.Y));
                        
                        // 停止捕获
                        _isCapturingRegionCoordinates = false;
                        break;
                    }
                    
                    // 检查ESC键是否按下（取消捕获）
                    if ((GetAsyncKeyState(0x1B) & 0x8000) != 0) // 0x1B 是ESC键的虚拟键码
                    {
                        _isCapturingRegionCoordinates = false;
                        Growl.Warning("已取消大区坐标捕获");
                        break;
                    }
                    
                    Thread.Sleep(100);
                }
            });
        }

        private void SaveRegionCoordinates(Point coordinates)
        {
            if (!_isCapturingRegionCoordinates || string.IsNullOrEmpty(_currentRegionName) || _currentRegionCoordinatesTextBlock == null)
                return;

            // 将屏幕坐标转换为客户端相对坐标
            System.Drawing.Point clientPoint = ScreenToClientCoordinates(new System.Drawing.Point((int)coordinates.X, (int)coordinates.Y));
            Point clientCoordinates = new Point(clientPoint.X, clientPoint.Y);

            switch (_currentRegionName)
            {
                case "艾欧尼亚":
                    _regionCoordinates.Ionia = clientCoordinates;
                    break;
                case "祖安":
                    _regionCoordinates.Zaun = clientCoordinates;
                    break;
                case "诺克萨斯":
                    _regionCoordinates.Noxus = clientCoordinates;
                    break;
                case "班德尔城":
                    _regionCoordinates.BandleCity = clientCoordinates;
                    break;
                case "皮尔特沃夫":
                    _regionCoordinates.Piltover = clientCoordinates;
                    break;
                case "战争学院":
                    _regionCoordinates.WarCollege = clientCoordinates;
                    break;
                case "巨神峰":
                    _regionCoordinates.MountTargon = clientCoordinates;
                    break;
                case "雷瑟守备":
                    _regionCoordinates.LeiSe = clientCoordinates;
                    break;
                case "裁决之地":
                    _regionCoordinates.Judgment = clientCoordinates;
                    break;
                case "黑色玫瑰":
                    _regionCoordinates.BlackRose = clientCoordinates;
                    break;
                case "暗影岛":
                    _regionCoordinates.ShadowIsles = clientCoordinates;
                    break;
                case "钢铁烈阳":
                    _regionCoordinates.IronSun = clientCoordinates;
                    break;
                case "水晶之痕":
                    _regionCoordinates.CrystalScar = clientCoordinates;
                    break;
                case "均衡教派":
                    _regionCoordinates.Equilibrium = clientCoordinates;
                    break;
                case "影流":
                    _regionCoordinates.ShadowStream = clientCoordinates;
                    break;
                case "守望之海":
                    _regionCoordinates.WatchSea = clientCoordinates;
                    break;
                case "征服之海":
                    _regionCoordinates.ConquerSea = clientCoordinates;
                    break;
                case "卡拉曼达":
                    _regionCoordinates.Kalamanda = clientCoordinates;
                    break;
                case "皮城警备":
                    _regionCoordinates.PiltoverPolice = clientCoordinates;
                    break;
                case "比尔吉沃特":
                    _regionCoordinates.Bilgewater = clientCoordinates;
                    break;
                case "德玛西亚":
                    _regionCoordinates.Demacia = clientCoordinates;
                    break;
                case "弗雷尔卓德":
                    _regionCoordinates.Freljord = clientCoordinates;
                    break;
                case "无畏先锋":
                    _regionCoordinates.FearlessPioneer = clientCoordinates;
                    break;
                case "恕瑞玛":
                    _regionCoordinates.Shurima = clientCoordinates;
                    break;
                case "扭曲丛林":
                    _regionCoordinates.TwistedTreeline = clientCoordinates;
                    break;
                case "巨龙之巢":
                    _regionCoordinates.DragonNest = clientCoordinates;
                    break;
                case "男爵领域":
                    _regionCoordinates.BaronRealm = clientCoordinates;
                    break;
                case "峡谷之巅":
                    _regionCoordinates.CanyonPeak = clientCoordinates;
                    break;
                case "教育网专区":
                    _regionCoordinates.EduNet = clientCoordinates;
                    break;
            }

            _regionCoordinates.SaveToFile(REGION_COORDINATES_FILE);
            UpdateRegionCoordinatesDisplay();
            _isCapturingRegionCoordinates = false;
            _currentRegionName = "";
            _currentRegionCoordinatesTextBlock = null;
            
            // 显示提示
            Growl.Success($"已保存 {_currentRegionName} 的坐标: ({clientPoint.X}, {clientPoint.Y})");
        }

        private void CancelRegionCoordinatesCapture()
        {
            _isCapturingRegionCoordinates = false;
            _currentRegionName = "";
            _currentRegionCoordinatesTextBlock = null;
        }

        // 大区坐标捕获事件处理方法
        private void CaptureIoniaCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("艾欧尼亚", IoniaCoordinates);
        private void CaptureZaunCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("祖安", ZaunCoordinates);
        private void CaptureNoxusCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("诺克萨斯", NoxusCoordinates);
        private void CaptureBandleCityCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("班德尔城", BandleCityCoordinates);
        private void CapturePiltoverCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("皮尔特沃夫", PiltoverCoordinates);
        private void CaptureWarCollegeCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("战争学院", WarCollegeCoordinates);
        private void CaptureMountTargonCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("巨神峰", MountTargonCoordinates);
        private void CaptureLeiSeCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("雷瑟守备", LeiSeCoordinates);
        private void CaptureJudgmentCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("裁决之地", JudgmentCoordinates);
        private void CaptureBlackRoseCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("黑色玫瑰", BlackRoseCoordinates);
        private void CaptureShadowIslesCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("暗影岛", ShadowIslesCoordinates);
        private void CaptureIronSunCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("钢铁烈阳", IronSunCoordinates);
        private void CaptureCrystalScarCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("水晶之痕", CrystalScarCoordinates);
        private void CaptureEquilibriumCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("均衡教派", EquilibriumCoordinates);
        private void CaptureShadowStreamCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("影流", ShadowStreamCoordinates);
        private void CaptureWatchSeaCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("守望之海", WatchSeaCoordinates);
        private void CaptureConquerSeaCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("征服之海", ConquerSeaCoordinates);
        private void CaptureKalamandaCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("卡拉曼达", KalamandaCoordinates);
        private void CapturePiltoverPoliceCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("皮城警备", PiltoverPoliceCoordinates);
        private void CaptureBilgewaterCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("比尔吉沃特", BilgewaterCoordinates);
        private void CaptureDemaciaCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("德玛西亚", DemaciaCoordinates);
        private void CaptureFreljordCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("弗雷尔卓德", FreljordCoordinates);
        private void CaptureFearlessPioneerCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("无畏先锋", FearlessPioneerCoordinates);
        private void CaptureShurimaCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("恕瑞玛", ShurimaCoordinates);
        private void CaptureTwistedTreelineCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("扭曲丛林", TwistedTreelineCoordinates);
        private void CaptureDragonNestCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("巨龙之巢", DragonNestCoordinates);
        private void CaptureBaronRealmCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("男爵领域", BaronRealmCoordinates);
        private void CaptureCanyonPeakCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("峡谷之巅", CanyonPeakCoordinates);
        private void CaptureEduNetCoordinates_Click(object sender, RoutedEventArgs e) => StartRegionCoordinatesCapture("教育网专区", EduNetCoordinates);

        private void ImportRegionCoordinates_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*",
                Title = "选择要导入的大区坐标文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    string json = File.ReadAllText(openFileDialog.FileName);
                    _regionCoordinates = JsonSerializer.Deserialize<RegionCoordinates>(json);
                    _regionCoordinates.SaveToFile(REGION_COORDINATES_FILE);
                    UpdateRegionCoordinatesDisplay();
                    Growl.Success("大区坐标导入成功");
                }
                catch (Exception ex)
                {
                    Growl.Error($"导入大区坐标失败: {ex.Message}");
                }
            }
        }

        private void ExportRegionCoordinates_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*",
                Title = "选择保存大区坐标的位置",
                FileName = "region_coordinates.json"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    string json = JsonSerializer.Serialize(_regionCoordinates, new JsonSerializerOptions { WriteIndented = true });
                    File.WriteAllText(saveFileDialog.FileName, json);
                    Growl.Success("大区坐标导出成功");
                }
                catch (Exception ex)
                {
                    Growl.Error($"导出大区坐标失败: {ex.Message}");
                }
            }
        }

        // 根据服务器名称获取坐标
        private System.Drawing.Point GetServerCoordinates(string serverName)
        {
            // 加载大区坐标
            RegionCoordinates regionCoordinates = RegionCoordinates.LoadFromFile(REGION_COORDINATES_FILE);
            
            // 根据服务器名称返回对应的坐标
            switch (serverName)
            {
                case "艾欧尼亚":
                    return new System.Drawing.Point((int)regionCoordinates.Ionia.X, (int)regionCoordinates.Ionia.Y);
                case "祖安":
                    return new System.Drawing.Point((int)regionCoordinates.Zaun.X, (int)regionCoordinates.Zaun.Y);
                case "诺克萨斯":
                    return new System.Drawing.Point((int)regionCoordinates.Noxus.X, (int)regionCoordinates.Noxus.Y);
                case "班德尔城":
                    return new System.Drawing.Point((int)regionCoordinates.BandleCity.X, (int)regionCoordinates.BandleCity.Y);
                case "皮尔特沃夫":
                    return new System.Drawing.Point((int)regionCoordinates.Piltover.X, (int)regionCoordinates.Piltover.Y);
                case "战争学院":
                    return new System.Drawing.Point((int)regionCoordinates.WarCollege.X, (int)regionCoordinates.WarCollege.Y);
                case "巨神峰":
                    return new System.Drawing.Point((int)regionCoordinates.MountTargon.X, (int)regionCoordinates.MountTargon.Y);
                case "雷瑟守备":
                    return new System.Drawing.Point((int)regionCoordinates.LeiSe.X, (int)regionCoordinates.LeiSe.Y);
                case "裁决之地":
                    return new System.Drawing.Point((int)regionCoordinates.Judgment.X, (int)regionCoordinates.Judgment.Y);
                case "黑色玫瑰":
                    return new System.Drawing.Point((int)regionCoordinates.BlackRose.X, (int)regionCoordinates.BlackRose.Y);
                case "暗影岛":
                    return new System.Drawing.Point((int)regionCoordinates.ShadowIsles.X, (int)regionCoordinates.ShadowIsles.Y);
                case "钢铁烈阳":
                    return new System.Drawing.Point((int)regionCoordinates.IronSun.X, (int)regionCoordinates.IronSun.Y);
                case "水晶之痕":
                    return new System.Drawing.Point((int)regionCoordinates.CrystalScar.X, (int)regionCoordinates.CrystalScar.Y);
                case "均衡教派":
                    return new System.Drawing.Point((int)regionCoordinates.Equilibrium.X, (int)regionCoordinates.Equilibrium.Y);
                case "影流":
                    return new System.Drawing.Point((int)regionCoordinates.ShadowStream.X, (int)regionCoordinates.ShadowStream.Y);
                case "守望之海":
                    return new System.Drawing.Point((int)regionCoordinates.WatchSea.X, (int)regionCoordinates.WatchSea.Y);
                case "征服之海":
                    return new System.Drawing.Point((int)regionCoordinates.ConquerSea.X, (int)regionCoordinates.ConquerSea.Y);
                case "卡拉曼达":
                    return new System.Drawing.Point((int)regionCoordinates.Kalamanda.X, (int)regionCoordinates.Kalamanda.Y);
                case "皮城警备":
                    return new System.Drawing.Point((int)regionCoordinates.PiltoverPolice.X, (int)regionCoordinates.PiltoverPolice.Y);
                case "比尔吉沃特":
                    return new System.Drawing.Point((int)regionCoordinates.Bilgewater.X, (int)regionCoordinates.Bilgewater.Y);
                case "德玛西亚":
                    return new System.Drawing.Point((int)regionCoordinates.Demacia.X, (int)regionCoordinates.Demacia.Y);
                case "弗雷尔卓德":
                    return new System.Drawing.Point((int)regionCoordinates.Freljord.X, (int)regionCoordinates.Freljord.Y);
                case "无畏先锋":
                    return new System.Drawing.Point((int)regionCoordinates.FearlessPioneer.X, (int)regionCoordinates.FearlessPioneer.Y);
                case "恕瑞玛":
                    return new System.Drawing.Point((int)regionCoordinates.Shurima.X, (int)regionCoordinates.Shurima.Y);
                case "扭曲丛林":
                    return new System.Drawing.Point((int)regionCoordinates.TwistedTreeline.X, (int)regionCoordinates.TwistedTreeline.Y);
                case "巨龙之巢":
                    return new System.Drawing.Point((int)regionCoordinates.DragonNest.X, (int)regionCoordinates.DragonNest.Y);
                case "男爵领域":
                    return new System.Drawing.Point((int)regionCoordinates.BaronRealm.X, (int)regionCoordinates.BaronRealm.Y);
                case "峡谷之巅":
                    return new System.Drawing.Point((int)regionCoordinates.CanyonPeak.X, (int)regionCoordinates.CanyonPeak.Y);
                case "教育网专区":
                    return new System.Drawing.Point((int)regionCoordinates.EduNet.X, (int)regionCoordinates.EduNet.Y);
                default:
                    return new System.Drawing.Point(0, 0);
            }
        }

        // 获取LOL客户端窗口的位置和大小
        private System.Drawing.Rectangle GetLOLClientWindowRect()
        {
            try
            {
                // 查找LOL客户端窗口
                Process[] processes = Process.GetProcessesByName("英雄联盟登录程序");
                if (processes.Length == 0)
                {
                    // 尝试查找LeagueClientUx进程
                    processes = Process.GetProcessesByName("Client");
                    if (processes.Length == 0)
                    {
                        Growl.Warning("未找到LOL客户端窗口，请确保客户端已启动");
                        return new System.Drawing.Rectangle(0, 0, 0, 0);
                    }
                }

                // 获取窗口句柄
                IntPtr hwnd = processes[0].MainWindowHandle;
                if (hwnd == IntPtr.Zero)
                {
                    // 如果主窗口句柄为空，尝试查找子窗口
                    hwnd = FindWindowByClass("RiotWindowClass");
                    if (hwnd == IntPtr.Zero)
                    {
                        Growl.Warning("无法获取LOL客户端窗口句柄");
                        return new System.Drawing.Rectangle(0, 0, 0, 0);
                    }
                }

                // 获取窗口位置和大小
                RECT rect;
                if (!GetWindowRect(hwnd, out rect))
                {
                    Growl.Warning("无法获取LOL客户端窗口位置");
                    return new System.Drawing.Rectangle(0, 0, 0, 0);
                }

                return new System.Drawing.Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
            }
            catch (Exception ex)
            {
                Growl.Warning($"获取LOL客户端窗口时出错: {ex.Message}");
                return new System.Drawing.Rectangle(0, 0, 0, 0);
            }
        }

        // 将屏幕坐标转换为客户端相对坐标
        private System.Drawing.Point ScreenToClientCoordinates(System.Drawing.Point screenPoint)
        {
            System.Drawing.Rectangle clientRect = GetLOLClientWindowRect();
            if (clientRect.Width == 0 || clientRect.Height == 0)
            {
                return screenPoint; // 如果无法获取客户端窗口，则返回原始坐标
            }

            return new System.Drawing.Point(screenPoint.X - clientRect.Left, screenPoint.Y - clientRect.Top);
        }

        // 将客户端相对坐标转换为屏幕坐标
        private System.Drawing.Point ClientToScreenCoordinates(System.Drawing.Point clientPoint)
        {
            System.Drawing.Rectangle clientRect = GetLOLClientWindowRect();
            if (clientRect.Width == 0 || clientRect.Height == 0)
            {
                return clientPoint; // 如果无法获取客户端窗口，则返回原始坐标
            }

            return new System.Drawing.Point(clientPoint.X + clientRect.Left, clientPoint.Y + clientRect.Top);
        }

        // 在客户端窗口内移动鼠标并点击
        private void MoveMouseAndClickInClient(System.Drawing.Point clientPoint)
        {
            System.Drawing.Point screenPoint = ClientToScreenCoordinates(clientPoint);
            buke_km.MouseMove(screenPoint.X, screenPoint.Y);
            simulator.Mouse.LeftButtonClick();
        }

        // 在客户端窗口内输入文本
        private void InputTextInClient(string text)
        {
            buke_km.InputString(text);
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        [DllImport("user32.dll")]
        private static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        private IntPtr FindWindowByClass(string className)
        {
            return FindWindow(className, null);
        }

        private void ImportCoordinates_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*",
                Title = "选择要导入的坐标文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    string json = File.ReadAllText(openFileDialog.FileName);
                    coordinatesConfig = JsonSerializer.Deserialize<CoordinatesConfig>(json);
                    SaveCoordinatesConfig();
                    
                    // 更新所有坐标的显示
                    UpdateCoordinatesDisplay("QQLoginButtonCoordinates", $"({coordinatesConfig.QQLoginButton.X}, {coordinatesConfig.QQLoginButton.Y})");
                    UpdateCoordinatesDisplay("QQAccountFieldCoordinates", $"({coordinatesConfig.QQAccountField.X}, {coordinatesConfig.QQAccountField.Y})");
                    UpdateCoordinatesDisplay("QQPasswordFieldCoordinates", $"({coordinatesConfig.QQPasswordField.X}, {coordinatesConfig.QQPasswordField.Y})");
                    UpdateCoordinatesDisplay("LoginButtonCoordinates", $"({coordinatesConfig.LoginButton.X}, {coordinatesConfig.LoginButton.Y})");
                    UpdateCoordinatesDisplay("ServerListButtonCoordinates", $"({coordinatesConfig.ServerListButton.X}, {coordinatesConfig.ServerListButton.Y})");
                    UpdateCoordinatesDisplay("ConfirmSelectionButtonCoordinates", $"({coordinatesConfig.ConfirmSelectionButton.X}, {coordinatesConfig.ConfirmSelectionButton.Y})");
                    
                    Growl.Success("坐标导入成功");
                }
                catch (Exception ex)
                {
                    Growl.Error($"导入坐标失败: {ex.Message}");
                }
            }
        }

        private void ExportCoordinates_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*",
                Title = "选择保存坐标的位置",
                FileName = "coordinates.json"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    string json = JsonSerializer.Serialize(coordinatesConfig, new JsonSerializerOptions { WriteIndented = true });
                    File.WriteAllText(saveFileDialog.FileName, json);
                    Growl.Success("坐标导出成功");
                }
                catch (Exception ex)
                {
                    Growl.Error($"导出坐标失败: {ex.Message}");
                }
            }
        }
    }
    
    // 坐标配置类
    public class CoordinatesConfig
    {
        public System.Drawing.Point QQLoginButton { get; set; } = new System.Drawing.Point(960, 540);
        public System.Drawing.Point QQAccountField { get; set; } = new System.Drawing.Point(960, 480);
        public System.Drawing.Point QQPasswordField { get; set; } = new System.Drawing.Point(960, 520);
        public System.Drawing.Point LoginButton { get; set; } = new System.Drawing.Point(960, 560);
        public System.Drawing.Point ServerListButton { get; set; } = new System.Drawing.Point(960, 400);
        public System.Drawing.Point ConfirmSelectionButton { get; set; } = new System.Drawing.Point(960, 500);
        public int ServerListStartY { get; set; } = 300;
        public int ServerListX { get; set; } = 960;
        public int ServerListInterval { get; set; } = 30;
        
        // 检查配置是否有效
        public bool IsValid()
        {
            // 检查所有坐标是否有效（不为0,0）
            if (QQLoginButton.X == 0 && QQLoginButton.Y == 0) return false;
            if (QQAccountField.X == 0 && QQAccountField.Y == 0) return false;
            if (QQPasswordField.X == 0 && QQPasswordField.Y == 0) return false;
            if (LoginButton.X == 0 && LoginButton.Y == 0) return false;
            if (ServerListButton.X == 0 && ServerListButton.Y == 0) return false;
            if (ConfirmSelectionButton.X == 0 && ConfirmSelectionButton.Y == 0) return false;
            if (ServerListStartY == 0) return false;
            if (ServerListX == 0) return false;
            if (ServerListInterval == 0) return false;
            
            return true;
        }
    }
}
